package com.lin.util;

import com.alibaba.fastjson.JSON;
import com.lin.base.Result;
import com.lin.base.ResultCode;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseMessageUtils {
    public static void setFailMessage(HttpServletResponse httpServletResponse, ResultCode resultCode, String message) throws IOException {

        setReadyResponse(httpServletResponse);
        PrintWriter printWriter = httpServletResponse.getWriter();
        String body = JSON.toJSONString(Result.fail(resultCode, message));
        printWriter.write(body);
        printWriter.flush();
    }

    public static void setSuccessfulMessage(HttpServletResponse httpServletResponse, String message) throws IOException {

        setReadyResponse(httpServletResponse);
        PrintWriter printWriter = httpServletResponse.getWriter();
        String body = JSON.toJSONString(Result.ok(message));
        printWriter.write(body);
        printWriter.flush();
    }

    private static void setReadyResponse(HttpServletResponse httpServletResponse) {
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
    }
}

